package com.dhcc.core.framework.result;

import java.util.LinkedHashMap;
import java.util.Map;

import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.core.framework.result.page.PageBT;
import com.dhcc.core.framework.util.JsonUtil;

import cn.hutool.core.bean.BeanUtil;

/**
 * 返回数据
 * 
 * @ClassName: R
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午9:30:41
 */
public class R extends LinkedHashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public R() {
        put("code", 200);
        put("message", "操作成功");
    }

    public static R error() {
        return error(500, "未知异常，请联系管理员");
    }

    public static R error(String message) {
        return error(500, message);
    }

    public static R error(int code, String message) {
        R r = new R();
        r.put("code", code);
        r.put("message", message);
        return r;
    }

    public static R ok(String message) {
        R r = new R();
        r.put("message", message);
        return r;
    }

    public static R ok(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

    public static R ok() {
        return new R();
    }
    
    public R data(Object obj) {
        super.put("data",obj);
        return this;
    }

    /**
     * 把service层的分页信息，封装为bootstrap table通用的分页封装
     */
    public static <T> PageBT<T> packForBT(Page<T> page) {
        return new PageBT<T>(page);
    }

    @Override
    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public R putObject(Object obj) {
        super.putAll(BeanUtil.beanToMap(obj));
        return this;
    }


    public Integer getCode() {
        return (Integer) this.get("code");
    }

    public String getMessage() {
        return (String) this.get("message");
    }

    public boolean isSuccess() {
        return this.getCode()==200;
    }

    public String toJsonString() {
        return JsonUtil.toJsonStr(this);
    }
    
}
